﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Repositories;

using MvcEngine.Core.Content;

namespace MvcEngine.LinqToSqlProvider
{
    public class ControlRepository : Repository, IControlRepository
    {
        public Control Get(Guid id)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Controls().Single(t => t.Id == id);
            }
        }

        public void Add(Control control)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Controls().InsertOnSubmit(control);
                contextManager.Commit();
            }
        }

        public void Delete(Guid moduleId)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Controls().DeleteOnSubmit(contextManager.Context.Controls().Single(t => t.ModuleId == moduleId));
                contextManager.Commit();
            }
        }

        public IList<Control> GetAll()
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Controls().ToList();
            }
        }

        public IList<Control> GetAllByModule(Guid moduleId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Controls().Where(c => c.ModuleId == moduleId).ToList();
            }
        }

        public Control GetByKey(string controlKey)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Controls().SingleOrDefault(c => c.ControlKey == controlKey);
            }
        }
    }
}
